package bean;

import javax.servlet.http.HttpServletRequest;
import java.util.Hashtable;


import java.lang.reflect.*;
import annotations.Form;
import annotations.Req;

public class Valider {

	public static boolean form(HttpServletRequest request, Object o) {
		boolean res = true;
		
		try {
			Class<? extends Object> c = o.getClass();
			Field[] fields = c.getDeclaredFields();
			for (int i=0; i<fields.length; i++) {
				if (fields[i].isAnnotationPresent(Form.class)) {
					String val = request.getParameter(fields[i].getName());
					if (val == null) val = "";
					if (fields[i].isAnnotationPresent(Req.class)) {
						if (val.trim().equals("")) {
							Method getErr = c.getMethod("getErr");
							Hashtable<String, String> err = (Hashtable<String, String>) getErr.invoke(o);
							Req ann = (Req)fields[i].getAnnotation(Req.class);
							err.put(fields[i].getName(), ann.mess());
							res = false;
						}
					}
				}
			}
		}
		catch (Exception e) {
			res = false;
		}
		
		return res;
	}
}
